package com.fortune.cat.service;

import com.fortune.cat.jooq.tables.pojos.TbUser;
import org.jooq.DSLContext;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

/**
 * @author zhaozeyang
 * @date 2019/4/28 19:03
 * @description
 */
@Component
public class UserService {

    private final com.fortune.cat.jooq.tables.TbUser tbUser = com.fortune.cat.jooq.tables.TbUser.TB_USER;

    private final DSLContext dsl;


    private static final ThreadLocal<TbUser> TB_USER_THREAD_LOCAL = new ThreadLocal<>();

    public UserService(DSLContext dsl) {
        this.dsl = dsl;
    }

    public static String currentUserId() {
        return TB_USER_THREAD_LOCAL.get().getId().toString();
    }

    public static TbUser currentUser() {
        return TB_USER_THREAD_LOCAL.get();
    }

    public void setUser(String userId) {
        List<TbUser> userList = dsl.select().from(tbUser)
                .where(tbUser.ID.eq(Long.valueOf(userId)))
                .fetch()
                .into(TbUser.class);
        Optional.ofNullable(userList)
                .ifPresent(tbUsers -> {
                    if (tbUsers.size() > 0) {
                        TB_USER_THREAD_LOCAL.set(tbUsers.get(0));
                    }
                });
    }
}
